package com.tencreat.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.tencreat.common.config.AliyunConfig;
import com.tencreat.common.core.HttpResult;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

/****
 * 物流查看工具类
 */
@Slf4j
public class LogisticsUtils {

    public static HttpResult<?> checkLogistics(String no) {
        AliyunConfig aliyunConfig = AliyunConfig.getAliConfig();
        //请求地址 支持http 和 https 及 WEBSOCKET
        String host = aliyunConfig.getHost();
        // 【2】后缀
        String path = "/kdi";
        // 【3】开通服务后 买家中心-查看AppCode
        String appcode = aliyunConfig.getAppcode();
        String urlSend = host + path + "?no=" + no;
        try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            // 格式Authorization:APPCODE (中间是英文空格)
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                System.out.println("正常请求计费(其他均不计费)");
                System.out.println("获取返回的json:");
                System.out.print(json);
                Object res = JSONObject.parse(json);
                return HttpResult.ok(res);
            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String err = "";
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
                    err = "AppCode错误";
                    System.out.println("AppCode错误 ");
                } else if (httpCode == 400 && error.equals("Invalid Url")) {
                    err = "请求的 Method、Path 或者环境错误";
                    System.out.println("请求的 Method、Path 或者环境错误");
                } else if (httpCode == 400 && error.equals("Invalid Param Location")) {
                    err = "参数错误";
                    System.out.println("参数错误");
                } else if (httpCode == 403 && error.equals("Unauthorized")) {
                    err = "服务未被授权（或URL和Path不正确）";
                    System.out.println("服务未被授权（或URL和Path不正确）");
                } else if (httpCode == 403 && error.equals("Quota Exhausted")) {
                    err = "套餐包次数用完";
                    System.out.println("套餐包次数用完 ");
                } else {
                    System.out.println("参数名错误 或 其他错误");
                    err = "参数名错误 或 其他错误";
                    System.out.println(error);
                }
                return HttpResult.error(err);
            }

        } catch (MalformedURLException e) {
            System.out.println("URL格式错误");
        } catch (UnknownHostException e) {
            System.out.println("URL地址错误");
        } catch (Exception e) {
            log.error("物流查询错误，错误信息{}",e.getMessage());
        }
        return HttpResult.error("物流查询错误");
    }

    /**
     * 读取返回结果
     *
     * @param is
     * @return
     * @throws IOException
     */
    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }
}
